import datetime  # noqa: D100

from ..api.db_operator import DBOperator
from ..api.git_reader import GitReader


class CommitLogService:
    """负责将日志信息存储到数据库的抽象类."""

    def __init__(self, git_reader: GitReader, db_operator: DBOperator):
        """初始化 CommitLogService.

        Args:
            git_reader: GitReader 对象，用于读取 Git 仓库信息
            db_operator: DBOperator 对象，用于操作数据库
        """
        self.git_reader = git_reader
        self.db_operator = db_operator

    def start_import_commits(
        self,
        last_activity_after: datetime.datetime,
        log_start_date: datetime.datetime,
        log_end_date: datetime.datetime,
    ):
        """启动 commits 导入流程.

        since_repo_latest_active_date: 仓库最新活跃日期，过滤太久没更新的项目
        log_start_date: 日志开始日期
        log_end_date: 日志结束日期
        """
        ## 根据 since_repo_latest_active_date 过滤仓库
        repo_page = 1
        while True:
            repositories = self.git_reader.get_projects_from_gitlab(
                since_date=last_activity_after, page=repo_page
            )
            print(
                f"######### Fetched {len(repositories)} repositories in page {repo_page}"
            )

            console_log_count = 0
            for repository in repositories:
                console_log_count += 1
                print(
                    f"\n\nDealing with repository {repository.id} : {repository.repo_fullname} by ({console_log_count} of {len(repositories)})"
                )
                branches = self.git_reader.get_branches(repository.id)
                ## 获得仓库所有分支
                for branch in branches:
                    ## 根据分支和日期获得分支日志
                    print(f"Dealing with branch {branch}")
                    ## 根据分支和给定区间，获取日志
                    logs = self.git_reader.get_commits(
                        repo_id=repository.id,
                        branch=branch,
                        start_date=log_start_date,
                        end_date=log_end_date,
                    )

                    ## 插入日志
                    self.db_operator.insert_commit_logs(logs)

            ## 如果仓库为空，则跳出循环
            if len(repositories) == 0:
                break
            repo_page += 1

    # 其他抽象方法根据需要
